package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.qf.common.MyThreadLocal;
import com.qf.entity.ShoppingCart;
import com.qf.exception.CustomException;
import com.qf.mapper.ShoppingCartMapper;
import com.qf.service.ShoppingCartService;
import org.springframework.stereotype.Service;

@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {


    @Override
    public boolean sub(ShoppingCart shoppingCart) {
        //得到用户的id
        Long userId = MyThreadLocal.getCreateUser();
        shoppingCart.setUserId(userId);//设置购物车的用户id

        //想要减去的菜品id或者套餐id
        Long dishId = shoppingCart.getDishId();
        Long setmealId = shoppingCart.getSetmealId();

        //通过用户的id取出用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();

        if (dishId != null) {
            //需要减少的购物车的是菜品
            wrapper.eq(ShoppingCart::getDishId, dishId);
        } else {
            //减少购物车的是套餐
            wrapper.eq(ShoppingCart::getSetmealId, setmealId);
        }
        //通过传入的 id查询在购物车中想要减少的是菜还是套餐
        ShoppingCart cart = this.getOne(wrapper);

        if (cart == null) {
          throw new CustomException("没有数据");
        }
        //如果存在,获取购物车该商品里面数量
        Integer number = cart.getNumber();
        if (number<1){
            throw new CustomException("异常数据");
        }
        if (number>1){
            cart.setNumber(number - 1);
            //更新数据
            this.updateById(cart);
            return true;
        }
        this.remove(wrapper);
        return true;
    }
}